package cur.channel.client.netty;


import com.alibaba.fastjson.JSON;
import cur.channel.client.model.Message;
import cur.channel.client.model.GroupTaskMsg;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

/**
 * Created by gantianxing on 2015/12/18.
 */

@Component
public class NettyClientUtil {

    private static final Log log = LogFactory.getLog(NettyClientUtil.class);

    /**
     * 发送消息到服务器
     * @param msg
     */
    public void sendRandom(String msg){
        try{
            NettyManager.NettyEntity nettyClient = NettyServerMap.getRandomChannl();
            if(nettyClient!=null){
                if (nettyClient.channel != null) {
                    log.info("random send task.server address:"+nettyClient.channel.remoteAddress());
                    GroupTaskMsg taskMsg = new GroupTaskMsg();
                    taskMsg.setGroupId(nettyClient.getNettyProperties().getGroupId());
                    taskMsg.setClientId(NettyProperties.clientId);
                    taskMsg.setMsg(msg);
                    nettyClient.channel.writeAndFlush(JSON.toJSONString(new Message(taskMsg)));
                }
            }else
            {
                log.error("没有可用的服务");
            }

        } catch (Exception e){
            log.error("定时发起task任务失败",e);
        }
    }


}
